//
//  PushManager.swift
//  cangchu
//
//  Created by kang on 2021/11/30.
//

import Foundation
public class PushManager{
    
    private init(){}
    
    public static let share = PushConfig()
    
    //MARK: -API
    public func connect(){
        NetWorkService.getWebSocketUrl { webUrl in
            if !webUrl.isEmpty {
                SocketManager.share.connect(url: webUrl, callBack: self)
            }
        }
    }
    
    public func disconnect(){
        Logger.log(message: "断开连接.")
        SocketManager.share.disconnect()
    }
    
    public func destory(){
        SocketManager.share.destory()
    }
    
    public func sendMessage(str:String){
        SocketManager.share.send(content: str) {
            Logger.log(message: "send message success")
        }
    }
    
    public func sendMessage(message:Message){
        SocketManager.share.send(message: message) {
            Logger.log(message: "send message success")
        }
    }
    
    /**
     绑定账号
     */
    public func bindAccount(account:String){
        Logger.log(message: "绑定账号：\(account)")
        let message = MessageFactory.createBindMessage(account: account, alias: nil, tags:nil)
        sendMessage(message: message)
    }
    
    /**
     绑定别名
     */
    public func bindAlias(alias:String){
        Logger.log(message: "绑定别名:\(alias)")
        let message = MessageFactory.createBindMessage(account: nil, alias: alias, tags: nil)
        sendMessage(message: message)
    }
    
    /**
     绑定标签
     */
    public func bindTags(tags:[String]){
        Logger.log(message: "绑定标签:\(tags)")
        let message = MessageFactory.createBindMessage(account: nil, alias: nil, tags: tags)
        sendMessage(message: message)
    }
    
    /**
     解绑类型 account:0, alias:1, tags:2
     */
    public func unBind(type:Int){
        let message = MessageFactory.createUnBindMessage(type: type)
        sendMessage(message: message)
    }
}

//MARK: -本地配置相关
extension PushManager{
    
    /**
     初始化，绑定应用信息
     */
    public func setInitParams(appid:String,secretKey:String){
        PushConfig.meAppid = appid
        PushConfig.meSecretKey = secretKey
    }
    
    /**
     是否响铃
     */
    public func setEnSound(isSound:Bool){
        PushConfig.isSound = isSound
    }
    
    /**
     是否打印日志
     */
    public func enableLog(enable:Bool){
        Logger.enableLog = enable
    }
    
    /**
     是否展示通知
     */
    public func showNotify(show:Bool){
        PushConfig.isShowNotify = show
    }
}

//MARK: -socket连接回调 以及接收消息回调
extension PushManager: SocketCallBack{
    
    /**
     连接socket 结果回调
     */
    public func connect(status: SocketStatus) {
        switch status {
        case .noConn:
            break
        case .connSuccess:
            Logger.log(message: "socket connect success.")
            Logger.log(message: "开始注册设备...")
            registerDevice()
            SocketManager.share.sendHeartMessage()
            break
        case .connError(let reson, let code):
            Logger.log(message: "socket connect error \(reson),code:\(code)")
            Logger.log(message: "socket reconnect ...")
            SocketManager.share.reconnect()
            break
        }
    }
    
    /**
     收到消息的回调
     */
    public func messsage(content: String) {
        Logger.log(message: "reciver new message \(content)")
        
        let message = json2Model(Message.self, json: content)
        
        switch message.messageType {
        case .BIND ,.RECEIPT ,.AUTH, .TEXT, .CUSTOM:
            sendFeedBackMessage(id: message.recordId!)
            break
        case .NOTICE:
            sendFeedBackMessage(id: message.recordId!)
            NotifyManager.share.notify(text: content)
            break
        case .NONE:
            break
        case .HEARTBEAT:
            break
        }
    }
    
    /**
     回执消息
     */
    public func sendFeedBackMessage(id:String){
        let message = MessageFactory.createFeedBackMessage(id: id)
        sendMessage(message: message)
    }
    
    /**
     socket 连接成功后，注册设备信息
     */
    public func registerDevice(){
        let message = MessageFactory.createConnectMessage()
        sendMessage(message: message)
    }
}
